package com.well.register.cluster;

import com.well.register.config.ClusterPropertiesConfig;
import com.well.register.data.DataCenter;
import com.well.rpc.model.ClusterServerModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class ClusterConfig {

    @Resource
    private ClusterPropertiesConfig clusterPropertiesConfig;

    /**
     * 处理集群配置
     *
     * @return
     */
    public List<ClusterServerModel> getClusterServer() {
        List<ClusterServerModel> serverModels = new ArrayList<>();
        String[] ipAdds = clusterPropertiesConfig.getAddr().split(",");
        if (ipAdds.length == 0) {
            log.warn("Cluster Address Is Null");
        }
        for (String ipAddr : ipAdds) {
            String[] ipAndPort = ipAddr.split(":");
            if (ipAndPort.length < 2) {
                throw new IllegalArgumentException("Invalid IP Address :" + ipAddr);
            }
            ClusterServerModel clusterServerModel = new ClusterServerModel();
            clusterServerModel.setHost(ipAndPort[0]);
            clusterServerModel.setPort(Integer.parseInt(ipAndPort[1]));
            serverModels.add(clusterServerModel);
        }
        //待优化
        return serverModels;
    }

    public boolean isEnable() {
        return clusterPropertiesConfig.getEnable();
    }
}
